"""
@Project:p7_2109
@File:jwt_auth.py
@Author:马可
@Date:下午 03:15
"""
import redis
from flask import request, g
from common.uitils.jwt_util import check_token,_generate_token

def jwt_authentication():
    """
    验证token
    在获取用户信息前验证前端发起请求携带的token,是否和后端生成的一样
    """
    token = request.headers.get('Authorization')
    if token:
        payload = check_token(token[4:1])
        print('auth payload--->', payload)
        if payload:
            # token 校验成功, 把用户id 写入g 对象
            # print('g.user_id--->',payload.get('id'))
            g.user_id = payload.get('id')
            print("g.is_fresh==>",g.is_refresh)
            # 判断是否是刷新生成的token, 获取不到返回false
            g.is_refresh = payload.get('is_refresh', False)
            print("g.is_fresh===>", g.is_refresh)
            # 从redis获取用户token
            rds = redis.Redis()
            rds_token = rds.get("user:%s:token" % (g.user_id))
            print('rds_token>>>',rds_token)
            if rds_token:
                if token != rds_token.decode('utf-8'):
                    print('两次token 不一样')
                    # 此时说明当前用户请求携带的token与Redis中的token不一致
                    return {"message": '没有权限访问', "code": 403}
            else:
                pass
        else:
            # 校验没通过
            # token过期,需要重新生成token
            payload_ = {
                'is_refresh':True
            }
            _, refresh_token = _generate_token(payload_, is_refresh=True)
            # 把生成的刷新token重新给请求头中的token
            request.headers['Authorization'] = refresh_token


